<template>
    <div class="orderDetail">
        <div class="orderDetail-header">
            <div class="search-inp">
                <div class="item">
                    <span class="item-text">订单信息</span>
                    <input type="text" v-model="orderNumberValue" placeholder="订单遍号">
                </div>
                <div class="item">
                    <span class="item-text">手机号</span>
                    <input type="text" v-model="phoneValue" placeholder="手机号">
                </div>
                <div class="item">
                    <span class="item-text">*创建时间</span>
                    <el-date-picker
                        v-model="ordercycleValue"
                        type="date"
                        placeholder="选择日期"
                        format="yyyy 年 MM 月 dd 日"
                        value-format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                </div>
                <div class="item">
                    <span class="item-text">订单状态</span>
                    <el-select v-model="searchvalue1" placeholder="全部">
                        <el-option  v-for="item in searchoptions1"  :key="item.value"  :label="item.label"  :value="item.value"></el-option>
                    </el-select>
                </div>
                <div class="item">
                    <span class="item-text">商品名称</span>
                    <input type="text" v-model="searchvalue2" placeholder="支持选择和模糊搜索">
                </div>
                <div class="item">
                    <span class="item-text">*自提点名称</span>
                    <input type="text" v-model="searchvalue3" placeholder="支持选择和模糊搜索">
                </div>
            </div>
            <div class="search-btn">
                <span class="my-btn" @click="screen" :class="colorBlue == 0?'my-back-blue':''" @mousemove="mouseMove(0)">筛选</span>
                <span class="my-btn" @click="emptyClick" :class="colorBlue == 1?'my-back-blue':''" @mousemove="mouseMove(1)">清空</span>
                <span class="my-btn" @click="handleExport" :class="colorBlue == 2?'my-back-blue':''" @mousemove="mouseMove(2)">导出</span>
                <!-- <span class="my-btn" :class="colorBlue == 3?'my-back-blue':''" @mousemove="mouseMove(3)">打印</span> -->
            </div>
        </div>
        <div class="table-box" v-if="orderDetailData">
            <div style="border-bottom:1px solid #eee;padding-bottom:10px;padding-left:10px;color:#777;font-size:13px;">共 {{orderDetailData.total}} 个订单</div>
            <el-table  :data="orderDetailData.list" style="width: 100%" >
                <el-table-column type="expand">
                    <template slot-scope="props">
                        <div @click="tableClick(props.row)">
                            <el-table :data="props.row.products" border stripe style="width: 100%" :span-method="arraySpanMethod">
                                <el-table-column  label="商户名称" >
                                    <template slot-scope="scope">
                                        <div class="productNameBox">
                                            <div class="img-box">
                                                <img :src="scope.row.image" alt="">
                                            </div>
                                            <div class="name">
                                                <p>{{scope.row.productName}}</p>
                                                <p>{{scope.row.skuName}}</p>
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column  prop="originalPrice"  label="原价" width="80"></el-table-column>
                                <el-table-column  prop="productPrice"  label="现价" width="80"></el-table-column>
                                <el-table-column  prop="number"  label="数量" width="80"></el-table-column>
                                <el-table-column  label="订单状态">
                                    <template slot-scope="scope">
                                        <span v-if="scope.row.state==0">待付款</span>
                                        <span v-if="scope.row.state==1">未支付已自动取消订单</span>
                                        <span v-if="scope.row.state==2">商家已接单（显示配送时间）</span>
                                        <span v-if="scope.row.state==3">商家配送中</span>
                                        <span v-if="scope.row.state==4">商家已送达（代取货）</span>
                                        <span v-if="scope.row.state==5">待评价</span>
                                        <span v-if="scope.row.state==6">已完成</span>
                                        <span v-if="scope.row.state==7">退款中</span>
                                        <span v-if="scope.row.state==8">退款成功</span>
                                        <span v-if="scope.row.state==9">用户取消订单</span>
                                    </template>
                                </el-table-column>
                                <el-table-column  label="收货人信息">
                                    <template slot-scope="scope">
                                        <div>
                                            <p>{{scope.row.receiveName}}</p>
                                            <p>{{scope.row.receivePhone}}</p>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column  prop="remark"  label="备注"></el-table-column>
                                <el-table-column  fixed="right"  label="操作"  width="100">
                                    <template slot-scope="scope">
                                        <el-button v-show="scope.row.state==2 || scope.row.state==3 || scope.row.state==4
                                         || scope.row.state==6" @click="handleClick()" type="text">退款</el-button>
                                        <el-button @click="godetail()" type="text">查看明细</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div>合计：Y{{props.row.orderPrice}}元
                                （打包费￥{{props.row.riderCommission}}元，
                                配送费￥{{props.row.packingPrice}}元)</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column  prop="orderNo"  label="订单编号"  width="300"></el-table-column>
                <el-table-column  prop="siteName"  label="自提点"  width="180"></el-table-column>
                <el-table-column  prop="createTime"  label="创建时间"></el-table-column>
                <el-table-column  prop="distributionTime"  label="预计收货时间"></el-table-column>
            </el-table>
            <el-pagination :page-size="pageSize"  @size-change="handleSizeChange"  @current-change="handleCurrentChange"  
            :current-page.sync="currentPage"  :page-sizes="[5, 10, 15, 20]"  layout="total, sizes, prev, pager, next, jumper"  
            :total="total"></el-pagination>
        </div>
        <!-- 弹窗 -->
        <div class="mask" v-show="masknum">
            <div class="content">
                <p class="content-top">
                    <span>仅退款订单处理</span>
                    <span @click="goback"><img src="../assets/img/error.png" alt=""></span>
                </p>
                <div class="content-text">
                    <span>订单编号 {{maskData.orderFormid}}</span>
                    <span>自提点：{{maskData.siteName}}</span>
                    <span>预计收货时间：{{maskData.signTime}}</span>
                </div>
                <div class="content-table">
                    <el-table  :data="maskData.products" @selection-change="handleSelectionChange"  border  style="width: 100%" >
                        <el-table-column  type="selection"  width="55"></el-table-column>
                        <el-table-column  label="商户名称" >
                            <template slot-scope="scope">
                                <div class="productNameBox">
                                    <div class="img-box">
                                        <img :src="scope.row.image?scope.row.image : '' " :onerror="logo" alt="">
                                    </div>
                                    <div class="name">
                                        <p>{{scope.row.productName}}</p>
                                        <p>{{scope.row.skuName}}</p>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column  prop="originalPrice"  label="原价"  width="120"></el-table-column>
                        <el-table-column  prop="productPrice"  label="现价"  width="120"></el-table-column>
                        <el-table-column  prop="number"  label="数量"  width="120"></el-table-column>
                        <el-table-column  label="退货数量"  width="120" >
                            <template slot-scope="scope">
                                <input style="width:50px;" type="text" v-model="scope.row.refund">
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="content-text">
                    <span>总退款金额：{{refundobj.backPrice}}元，退款数量{{backPrice}}</span>
                    <span>自提点：{{maskData.siteName}}</span>
                </div>
                <div class="content-bz">
                    <p>备注（非必填）</p>
                    <textarea v-model="refundobj.remark"></textarea>
                </div>
                <div class="content-btn">
                    <span class="my-btn" @click="goback">返回</span>
                    <span class="my-btn my-back-blue" @click="sureClick">确定</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data(){
        return{
            queryParams: {
                createTime: this.ordercycleValue,
                orderNo: this.orderNumberValue,//订单编号
                page: this.page,//日期
                pageSize:this.pageSize,
                productName: this.searchvalue2,//商品名称
                receivePhone: this.phoneValue,//收货人手机号
                siteName: this.searchvalue3,//自提点名称
                state: this.searchvalue1,//状态
            },
            colorBlue:0,
            logo:'this.src="' + require('../assets/img/img.png') + '"',
            masknum:false,//弹窗
            maskData:'',//退货数据
            maskRemark:'',//退货备注
            masktablenum:true,
            orderDetailData:'',//订单数据列表
            phoneValue:'',//手机号
            orderNumberValue:'',//订单号搜索
            ordercycleValue:'',//订单周期搜索
            searchvalue1:'null',//订单状态选中值
            searchvalue2:'',//商品名称选中值
            searchvalue3:'',//自提点名称选中值
            searchoptions1:[//状态选择值
                {label:'全部',value:'null'},
                {label:'商家已接单',value:'2'},
                {label:'商家配送中',value:'3'},
                {label:'商家已送达（代取货）',value:'4'},
                {label:'待评价',value:'5'},
                {label:'已完成',value:'6'},
                {label:'退款中',value:'7'},
                {label:'售后',value:'8'},
                {label:'取消订单',value:'9'}
            ],
            multipleSelection: [],//退款多选数组
            refundobj:{//退款传参
                "afterType": 1,
                "backPrice": 0,
                "orderId": '',
                "productParams": [],
                "remark": ""
            },
            backPrice:0,//退款数量
            //分页
            page:1,
            pageSize:5,
            currentPage:1,//跳转到第几页
            total:0,//总共几条
        }
    },
    mounted(){
        this.getorderDetailData()
    },
    methods:{
        handleExport() {
            // this.emptyClick();
            var param={
                "createTime": this.ordercycleValue,
                "orderNo": this.orderNumberValue,
                "page": this.page,
                "pageSize": this.pageSize,
                "productName": this.searchvalue2,
                "receivePhone": this.phoneValue,
                "siteName": this.searchvalue3,
                "state": this.searchvalue1
            }
            let { page,pageSize,...params } = param//后台不要分页，去掉
            this.axios({
                url:'/order/orderList',
                method:'post',
                data: JSON.stringify(param),
            }).then(res=>{
                if(res.data.code == '') {
                    this.$message({
                        /*导出数据量大时加提示，设置setTimeout延时 */
                        type: "info",
                        message: "正在导出，请稍候..."
                    });
                    setTimeout(() => {
                        import("../config/Export2Excel").then(excel => {
                            /* 设置Excel的表格第一行的标题 */
                            const tHeader = ["订单编号", "自提点", "预计收货时间", "创建时间", "总价", "收货人姓名", "收货人手机号",];
                            /* filterValue里的值是tableData里对象的属性 */
                            const filterValue = ["orderNo", "siteName", "distributionTime", "createTime", "orderPrice", "receiveName", "receivePhone",]; /*导出列表的字段 */
                        //处理二级数据
                            // 取出最大数据条数，别问为啥 不想去改源码
                            let length = 0;
                            for(let i = 0; i < this.pageSize; i++) {
                                if(length >= res.data.data.list[i].products.length) {
                                    length = length
                                }else {
                                    length = res.data.data.list[i].products.length
                                }
                            }
                            // 根据最大条数添加标题和字段  multiHeader和merges这里不需要就不处理了 
                            // 需要添加的下面字段multiHeader[0].push("标题", "和merges配合用的"); 这里没有就不说了
                            for(let j = 0; j < length; j++) {
                                res.data.data.list[0].products.forEach(item => {
                                    tHeader.push("商品名称", "原价", "商品现价", "商品数量",);
                                    filterValue.push('productName', 'originalPrice', 'productPrice', 'number',); // 对应的字段
                                })
                            }
                            let Data = res.data.data.list; /*请求接口返回导出数组 */
                            const list = Data;
                            //处理数据
                            // console.log(list, "products");
                            const data = this.format(list);//从新写的处理方法
                        //处理二级数据
                            // const data = this.formatJson(filterValue, list);//以前的方法
                            console.log(data)
                            excel.export_json_to_excel({
                                header: tHeader,
                                data,
                                filename: "订单明细列表"
                            });
                        });
                    }, 2000);
                }
            })
            
        },
        format(jsonData) { //数据处理 
            let dataList = [];
            for(let i = 0; i< jsonData.length; i++) {
                let list = [];
                list.push(jsonData[i].orderNo);
                list.push(jsonData[i].siteName);
                list.push(jsonData[i].distributionTime);
                list.push(jsonData[i].createTime);
                list.push(jsonData[i].orderPrice);
                list.push(jsonData[i].receiveName);
                list.push(jsonData[i].receivePhone);
                for (let j = 0; j < jsonData[i]['products'].length; j++) {
                    list.push(jsonData[i]['products'][j].productName);
                    list.push(jsonData[i]['products'][j].originalPrice);
                    list.push(jsonData[i]['products'][j].productPrice);
                    list.push(jsonData[i]['products'][j].number);
                }
                dataList.push(list);
            }
            return dataList;
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map((v) => filterVal.map((j) => v[j]));
        },

        //切换按钮样式
        mouseMove(index) {
            this.colorBlue = index;
        },
        //获取数据
        getorderDetailData(res){
            console.log(res)
            if(res == 1) {
                console.log(res)
                var param={
                    "createTime": this.ordercycleValue,
                    "orderNo": this.orderNumberValue,
                    "page": 1,
                    "pageSize": this.pageSize,
                    "productName": this.searchvalue2,
                    "receivePhone": this.phoneValue,
                    "siteName": this.searchvalue3,
                    "state": this.searchvalue1
                } 
            } else {
               var param={
                    "createTime": this.ordercycleValue,
                    "orderNo": this.orderNumberValue,
                    "page": this.page,
                    "pageSize": this.pageSize,
                    "productName": this.searchvalue2,
                    "receivePhone": this.phoneValue,
                    "siteName": this.searchvalue3,
                    "state": this.searchvalue1
                } 
            }
            console.log(param)
            this.axios({
                url:'/order/orderList',
                method:'post',
                data:JSON.stringify(param),
            }).then(res=>{
                console.log(res)
                this.orderDetailData=res.data.data
                this.total=res.data.data.total
                this.orderDetailData.list.forEach(e => {
                    e.products.forEach(ele=>{
                        ele.remark=e.remark
                        ele.receiveName=e.receiveName
                        ele.receivePhone=e.receivePhone
                        ele.state=e.state
                        ele.refund=ele.number
                    })
                });
            })
        },
         /** 导出按钮操作 */
		 
        handleExport() {//传driverOrderId
            //根据搜索条件导出
            var param={
                "createTime": this.ordercycleValue,
                "orderNo": this.orderNumberValue,
                "productName": this.searchvalue2,
                "receivePhone": this.phoneValue,
                "siteName": this.searchvalue3,
                "state": this.searchvalue1
            }
            // let { page,pageSize,...params } = param//后台不要分页，去掉
            this.axios({
                url:'/order/orderExcel',
                method:'post',
                data: JSON.stringify(param),
                responseType: 'blob'
            }).then(res=>{
                const blob = new Blob([res.data], { type: 'application/vnd.ms-excel,charset=utf-8'})
                console.log(res)
                console.log(blob)
                const fileName = '订单明细表.xlsx'
                if ('download' in document.createElement('a')) {
                    // 非IE下载
                    const elink = document.createElement('a')
                    console.log(elink)
                    elink.download = fileName
                    elink.style.display = 'none'
                    elink.href = URL.createObjectURL(blob)
                    document.body.appendChild(elink)
                    elink.click()
                    URL.revokeObjectURL(elink.href) // 释放URL 对象
                    document.body.removeChild(elink)
                } else {
                    // IE10+下载
                    navigator.msSaveBlob(blob, fileName)
                }
            })
        },
		
        //筛选
        screen() {
            this.handleCurrentChange(1)
            this.currentPage = 1
        },
        //清空
        emptyClick(){
            this.ordercycleValue=""
            this.orderNumberValue=""
            this.searchvalue2=""
            this.phoneValue=""
            this.searchvalue3=""
            this.searchvalue1="null"
            this.getorderDetailData(2)
            this.currentPage = 1
        },
        //去详情
        godetail(){
            setTimeout(()=>{
                var id=this.maskData.orderId
                console.log('id',this.maskData)
                this.$router.push('/index/orderDetails/'+id)
            },300)
        },
        //打开退款弹窗
        handleClick(){
            this.masknum=true
        },
        //多选退款数组
        handleSelectionChange(val){
            this.multipleSelection = val;
            var backPrice=0
            this.multipleSelection.forEach(e=>{
                backPrice+=e.refund*e.productPrice
                this.backPrice+=e.refund
                this.refundobj.productParams.push({
                    orderProductId:e.orderProductId,
                    backNumber:e.refund
                })
            })
            this.refundobj.backPrice=backPrice
            this.refundobj.orderId=this.maskData.orderId*1
        },
        //关闭退款弹窗
        goback(){
            this.masknum=false
            this.multipleSelection=[]
            this.refundobj={
                "afterType": 1,
                "backPrice": 0,
                "orderId": '',
                "productParams": [],
                "remark": ""
            }
            this.backPrice=0
        },
        //提交弹窗数据
        sureClick(){
            this.axios({
                url:'/order/orderReturn',
                method:'post',
                data:JSON.stringify(this.refundobj),
            }).then(res=>{
            })
        },
        //点击第二层表获取数据
        tableClick(a){
            this.maskData=a
        },
        //合并单元格
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 4||columnIndex === 5||columnIndex === 6||columnIndex === 7) {
                if (rowIndex === 0) {
                    return {rowspan: 10,colspan: 1};
                } else {
                    return {rowspan: 0,colspan: 0};
                }
            }
        },
        //当每页显示条数变化时触发
        handleSizeChange(val){
            this.pageSize=val
            this.getorderDetailData()
        },
        //当页数变化时触发
        handleCurrentChange(val){
            this.page=val
            this.getorderDetailData()
        },
    },
    watch:{
        
    }
}
</script>

<style scoped>
/* 搜索 */
.orderDetail-header{
    margin-top: 20px;
    display: flex;
    align-items: flex-start;
}
/* 搜索input框 */
.search-inp{
    display: flex;
    flex-wrap: wrap;
}
.search-inp .item{
    width: 330px;
    margin-bottom: 6px;
}
.search-inp .item-text{
    width: 100px;
    text-align: right;
    display: inline-block;
    margin-right: 10px;
}
/* 搜索按钮 */
.search-btn{
    width: 500px;
}
.search-btn span{
    margin-left: 8px;
    margin-bottom: 6px;
}
.search-btn span:hover{
    color: #777;
}
.search-btn span:first-child:hover{
    color: #eee;
}
/* 表格 */
.table-box{
    margin-top: 40px;
}
.img-box{
    width: 70px;
    height: 70px;
    /* background: #eee; */
    position: relative;
    overflow: hidden;
    margin-right: 8px;
}
.img-box img{
    width: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}
.productNameBox{
    display: flex;
    justify-content: space-between;
}
.productNameBox .name{
    text-align: center;
    width: calc( 100% - 78px);
}
.productNameBox .name p:first-child{
    height: 40px;
    line-height: 40px;
}
.productNameBox .name p:last-child{
    color: #aaa;
    font-size: 12px;
}
</style>
<style scoped>
/* 遮罩层 */
.mask{
    width: 100vw;
    height: 100vh;
    /* color: #555; */
    background: rgba(51, 51, 51, 0.692);
    position: fixed;
    z-index: 99;
    top: 0;
    left: 0;
    border-radius: 3px;
}
.mask .content{
    width: 790px;
    max-height: 90vh;
    overflow: auto;
    background: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    padding: 30px;
}
.mask .content-top{
    display: flex;
    justify-content: space-between;
    /* border-bottom: 1px solid #eee; */
    /* margin-bottom: 10px; */
}
.mask .content-top img{
    width: 25px;
}
.content-text{
    padding-top: 10px;
    padding-bottom: 10px;
}
.content-text span{
    color: #777;
    font-size: 13px;
    padding-right: 40px;
}
.content-bz p{
    font-size: 14px;
    margin-bottom: 8px;
    margin-top: 10px;
}
.content-bz textarea{
    width: 100%;
    padding: 5px;
    font-size: 14px;
}
.content-btn span{
    margin-right: 20px;
    margin-top: 10px;
}
</style>
<style>
.search-inp input{
    width: 190px;
}
.el-select{
    width: 190px;
}
.el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 190px;
}
</style>